import React, { useEffect, useState,useRef  } from 'react';
import Header from '../../conponents/header';
import Footter from '../../conponents/footter';
import bg from '../../assets/bg.jpg'
import Item from './components/item';
import { useParams,useLocation } from 'react-router-dom';
import Service from '../../conponents/service';
import axios from 'axios'
import Login from '../../conponents/login';
import classNames from 'classnames';
import { useTranslation } from 'react-i18next';
import { BASE_URL } from '../../utils/request';
import { Pagination,Input,Button } from 'antd';
import { LeftOutlined } from '@ant-design/icons';

import right from '../../assets/right.png'
import left from '../../assets/left.png'
import { Image } from 'antd'

const List = () => {
  const { Search } = Input;
  const { t } = useTranslation()

  const { type } = useParams()
  const [list, setList] = useState([])
  const token = localStorage.getItem('token') || ''
  const [showLogin, setShowLogin] = useState(false);
  const [area, setArea] = useState([]);
  const onCloseLogin = (e) => {
    setShowLogin(e)
  }
  const [params, setParams] = useState({
    pageNum: 1,
    pageSize: 12,
    location:null,
    education:null,
    startHeighut: null,
    endHeight: null,
    bloodData:null,
    name:null
  })
  const [showInfo,setShowInfo] = useState(false)
  const [total, setTotal] = useState(0)

  const getList = async () => {
    const url = type === 'OD' ? 'system/od/list' : type === 'SD' ? 'system/sm/list' : 'system/hospital/list'
    const res = await axios({
      url: BASE_URL + url,
      method: 'get',   // 默认值
      headers: {
        Authorization: `Bearer ${token}`
      },
      params
    })
    if (res.data.code === 200) {
      setList(res.data.rows)
      setTotal(res.data.total)
    }
    if (res.data.code === 401) {
      setShowLogin(true)
    }
  }
  const getArea = async ()=>{
    const url1 = 'system/dict/data/type/sys_location'
    const ress = await axios({
      url: BASE_URL + url1,
      method: 'get',   // 默认值
      headers: {
        Authorization: token
      },
      params
    })
    if (ress.data.code === 200) {
      ress.data.data.unshift({ dictLabel: '全部' })
      setArea(ress.data.data)
    }
    if (ress.data.code === 401) {
      setShowLogin(true)
    }
  }
  const educationData = [
    { dictLabel: `${t('全部')}` },
    { dictLabel: `${t('大专')}` },
    { dictLabel: `${t('本科')}` },
    { dictLabel: `${t('博士')}` },
    { dictLabel: `${t('硕士')}` },
  ]
  const bloodData = [
    { dictLabel: `${t('全部')}` },
    { dictLabel: 'A+' },
    { dictLabel: 'B+' },
    { dictLabel: 'AB+' },
    { dictLabel: 'O+' },
  ]
  const heightData = [
    { dictLabel: `${t('全部')}` },
    { dictLabel: '160-' },
    { dictLabel: '160~165' },
    { dictLabel: '165~170' },
    { dictLabel: '170+' },
  ]

  const [current1, setCurrent1] = useState(0)
  const [current2, setCurrent2] = useState(0)
  const [current3, setCurrent3] = useState(0)
  const [current4, setCurrent4] = useState(0)
  const select = (e, i, type) => {
    console.log(e, i, type,666);
    
    if (e === '全部' || e === 'all' || e=== 'ทั้งหมด') {
      e = null
    }
    if (type === 'location') {
      setParams({
        ...params,
        location: e
      })
      
      setCurrent1(i)
    } else if (type === 'education') {
      setParams({
        ...params,
        education: e
      })    
      setCurrent2(i)
    } else if (type === 'height') {
      console.log(e, 666);

      if (e === '160-') {
        setParams({
          ...params,
          startHeight: null,
          endHeight: 160
        })
      } else if (e === '160~165') {
        setParams({
          ...params,
          startHeight: 160,
          endHeight: 165
        })
      } else if (e === '165~170') {
        setParams({
          ...params,
          startHeight: 165,
          endHeight: 170
        })
      } else if (e === '170+') {
        setParams({
          ...params,
          startHeight: 170,
          endHeight: null
        })
      } else if (e === null) {
        setParams({
          ...params,
          startHeight: null,
          endHeight: null
        })
      }
      setCurrent3(i)
    }
    else if (type === 'blood') {
      setParams({
        ...params,
        blood: e
      })
      setCurrent4(i)
    }
  }
  useEffect(() => {
    getList()
    getArea()
  }, [type])
  useEffect(() => {
    getList()
    window.localStorage.setItem('params',JSON.stringify(params))
    
  }, [params])

  const onChange = (pageNumber) => {
    setParams({
      ...params,
      pageNum:pageNumber
    })
  };

  const onSearch = (e)=>{
    console.log(e);
    setParams({
      ...params,
      name:e
    })
  }

  const [id,setId] = useState(1)
  const [currentIndex, setCurrentIndex] = useState(0);
  const [item, setItem] = useState({})


  const getInfo = async () => {
    const url = type === 'OD' ? '/system/od/' + id : '/system/sm/' + id
    const res = await axios({
      url: BASE_URL + url,
      method: 'get',   // 默认值
      headers: {
        Authorization: token
      }
    })
    if (res.data.code === 200) {
      setItem(res.data.data)
    }
    if (res.data.code === 401) {
      setShowLogin(true)
    }
  }


  const showMedia = (index) => {
    setCurrentIndex(index);
  };

  const nextSlide = () => {
    setCurrentIndex((currentIndex + 1) % (item.photoFiles.length + 1));
    scrollContainerRef.current.scrollLeft +=30;

  };

  const prevSlide = () => {
    setCurrentIndex((currentIndex - 1 + item.photoFiles.length + 1) % (item.photoFiles.length + 1));
    scrollContainerRef.current.scrollLeft -=30;
  };
  const scrollContainerRef = useRef(null);
  const getScrollTop = ()=> {
    var scroll_top = 0;
    if (document.documentElement && document.documentElement.scrollTop) {
        scroll_top = document.documentElement.scrollTop;
    }
    else if (document.body) {
        scroll_top = document.body.scrollTop;
    }
    return scroll_top;
}

  const getId = (id)=>{
    window.localStorage.setItem('height',getScrollTop())
    window.scrollTo(0,0);
    setShowInfo(true)
    setId(id)
  }
  useEffect(() => {
    getInfo()
  }, [id])
  const back = ()=>{
    setShowInfo(false)
    setTimeout(()=>{
      window.scrollTo(0,window.localStorage.getItem('height'))
    },50)
  }
  return (
    <>
      <div style={{ backgroundImage: `url(${bg})` }} className='h-auto bg-no-repeat bg-cover py-20'>
        <Header />
        {!showInfo &&<div className='bg-[#79A581] p-4 rounded-lg w-[90%] sm:w-[60%] bottom-10 mx-auto mt-40 text-white'>
          <div className='flex items-center'>
            <div className='w-16 h-6 bg-[#728D6C] text-sm text-white leading-6 text-center'>{t('区域')}</div>
            <div className='h-6 w-6 border-t-[12px] border-t-transparent border-b-[12px] border-b-transparent border-l-[24px] border-l-[#728D6C]'></div>
            <div className='flex items-center flex-wrap flex-1'>
              {area.map((i, index) => <div key={i.dictLabel} onClick={() => select(i.dictLabel, index, 'location')}
                className={classNames('text-sm ml-5 cursor-pointer', current1 === index && 'text-orange-300')}>{t(i.dictLabel)}</div>)}
            </div>
          </div>
          {type !== 'hospital' && type !== 'SD' && <div className='flex items-center mt-4'>
            <div className='w-16 h-6 bg-[#728D6C] text-sm text-white leading-6 text-center'>{t('学历')}</div>
            <div className='h-6 w-6 border-t-[12px] border-t-transparent border-b-[12px] border-b-transparent border-l-[24px] border-l-[#728D6C]'></div>
            <div className='flex items-center flex-wrap flex-1'>
              {educationData.map((i, index) => <div key={i.dictLabel} onClick={() => select(i.dictLabel, index, 'education')}
                className={classNames('text-sm ml-5 cursor-pointer', current2 === index && 'text-orange-300')}>{i.dictLabel}</div>)}
            </div>

          </div>}
          {type !== 'hospital' && <div className='flex items-center mt-4'>
            <div className='w-16 h-6 bg-[#728D6C] text-sm text-white leading-6 text-center'>{t('身高')}</div>
            <div className='h-6 w-6 border-t-[12px] border-t-transparent border-b-[12px] border-b-transparent border-l-[24px] border-l-[#728D6C]'></div>
            <div className='flex items-center flex-wrap flex-1'>
              {heightData.map((i, index) => <div key={i.dictLabel} onClick={() => select(i.dictLabel, index, 'height')}
                className={classNames('text-sm ml-5 cursor-pointer', current3 === index && 'text-orange-300')}>{i.dictLabel}</div>)}
            </div>

          </div>}
          {type !== 'hospital' && <div className='flex items-center mt-4'>
            <div className='w-16 h-6 bg-[#728D6C] text-sm text-white leading-6 text-center'>{t('血型')}</div>
            <div className='h-6 w-6 border-t-[12px] border-t-transparent border-b-[12px] border-b-transparent border-l-[24px] border-l-[#728D6C]'></div>
            <div className='flex items-center flex-wrap flex-1'>
              {bloodData.map((i, index) => <div key={i.dictLabel} onClick={() => select(i.dictLabel, index, 'blood')}
                className={classNames('text-sm ml-5 cursor-pointer', current4 === index && 'text-orange-300')}>{i.dictLabel}</div>)}
            </div>
          </div>}
          {type !== 'hospital' &&<Search placeholder="请输入姓名" onSearch={onSearch} enterButton className='w-full mt-4' />}
        </div>}
      </div>
      {!showInfo && <div className='bg-[#E3F2DF] flex-1'>
        <div className='grid gap-x-4 gap-y-10 px-5 sm:px-20 py-10 grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4'>
          {type === 'OD' && <Item type={'OD'} list={list} getId={getId} />}
          {type === 'SD' && <Item type={'SD'} list={list} getId={getId} />}
          {type === 'hospital' && <Item type={'hospital'} list={list} getId={getId} />}
        </div>
        {list.length!==0&&<Pagination  className='pb-5'  align="center" defaultCurrent={params.pageNum} defaultPageSize={params.pageSize} total={total} onChange={onChange} showSizeChanger={false} showQuickJumper />}
      </div >}


      {showInfo && <div className="bg-[#E3F2DF] font-sans p-5">
        <div className="max-w-5xl mx-auto bg-white p-5 rounded-lg shadow-md flex flex-wrap">
          <div className="sm:w-64 w-full text-center bg-gray-200 rounded-lg p-2 sm:mr-5 flex flex-col justify-between">
            {item?.photoFiles?.length > 0 && <div className='relative h-[45%]'>
              <Image.PreviewGroup items={item.photoFiles.map((i, index) =>i.url)}
                preview={{
                  onChange: (current, prev) => {
                    current>currentIndex?scrollContainerRef.current.scrollLeft +=30:scrollContainerRef.current.scrollLeft -=30
                    setCurrentIndex(current)
                  }
                }}
              > 
                <Image src={item.photoFiles[currentIndex]?.url} alt="" height="350px" width="100%" className='object-cover' />
              </Image.PreviewGroup>
              <div className="absolute top-1/2 left-0 w-full flex justify-between transform translate-y-1/2">
                {currentIndex > 0 ?
                  <img src={left} className="bg-black bg-opacity-50 text-white p-2 cursor-pointer rounded-full w-10 ml-1" onClick={prevSlide} />
                  : <div></div>}
                {currentIndex < item.photoFiles.length - 1 &&
                  <img src={right} className="bg-black bg-opacity-50 text-white p-2 cursor-pointer rounded-full w-10 mr-1" onClick={nextSlide} />}
              </div>
              <div ref={scrollContainerRef} className="flex mt-2 sm:w-60 w-full overflow-x-auto overflow-y-hidden">
                {item.photoFiles.map((i, index) => (
                  <img
                    key={index}
                    src={i.url}
                    className={`${currentIndex === index ? 'border-blue-500 border-2' : ''} w-10 h-10 object-cover mx-1 rounded-md cursor-pointer transition-transform transform hover:scale-110`}
                    onClick={() => showMedia(index)}
                  />
                ))}
              </div>
            </div>}
            {item?.videoFiles?.length > 0 && <video className={currentIndex === item.videoFiles.length ? 'block w-full h-auto rounded-lg' : 'hidiven'} style={{ height: '48%', backgroundColor: '#000' }} controls>
              <source src={item.videoFiles[0]?.url} type="video/mp4" />
            </video>}
          </div>

          <div className="flex-1 flex flex-col justify-center">
            {/* OD页面 */}
            <h2 className="text-2xl text-gray-800 mb-2 border-b-2 border-[#E3F2DF] pb-1">{type}{t('详情')}</h2>
            {type === 'OD' && <div>
              <div className="mb-5">
                <div className="flex items-center">
                  <div>👤 {t('姓名')}：</div>
                  <div>{item.name}</div>
                </div>
                <div className="flex items-center">
                  <div>👤 {t('出生日期')}：</div>
                  <div>{item.birth}</div>
                </div>
                <div className="flex items-center">
                  <div>👤 {t('所在地')}：</div>
                  <div>{item.location}</div>
                </div>
                <div className="flex items-center">
                  <div>🩸 {t('血型')}：</div>
                  <div>{item.blood}</div>
                </div>
                <div className="flex items-center">
                  <div>🩸 {t('种族')}：</div>
                  <div>{item.race}</div>
                </div>
                <div className="flex items-center">
                  <div>📏 {t('身高')}：</div>
                  <div>{item.height}</div>
                </div>
                <div className="flex items-center">
                  <div>⚖️ {t('体重')}：</div>
                  <div>{item.weight}</div>
                </div>
                <div className="flex items-center">
                  <div>⚖️ {t('眼睛颜色')}：</div>
                  <div>{item.eyeColor}</div>
                </div>
                <div className="flex items-center">
                  <div>⚖️ {t('肤色')}：</div>
                  <div>{item.skinColor}</div>
                </div>
                <div className="flex items-center">
                  <div>⚖️ {t('发色')}：</div>
                  <div>{item.hairColor}</div>
                </div>
                <div className="flex items-center">
                  <div>⚖️ {t('母语')}：</div>
                  <div>{item.firstLanguage}</div>
                </div>
                {token && <div className="flex items-center">
                  <div>🪙 {t('价格')}：$</div>
                  <div>{item.price}</div>
                </div>}
                <div className="flex items-center">
                  <div>💍 {t('是否婚姻')}：</div>
                  <div>{item.maritalStatus === false ? `${t('未婚')}` : `${t('已婚')}`}</div>
                </div>
                <div className="flex items-center">
                  <div>💍 {t('是否整过')}：</div>
                  <div>{item.plastic == '0' ? '否' : item.plastic == '1' ? `${t('是')}` : ''}</div>
                </div>
                <div className="flex items-center">
                  <div>💍 {t('最高学历')}：</div>
                  <div>{item.education}</div>
                </div>
                <div className="flex items-center">
                  <div>💍 {t('大学名称')}：</div>
                  <div>{item.school}</div>
                </div>
                <div className="flex items-center">
                  <div>💍 {t('专业科系')}：</div>
                  <div>{item.speciality}</div>
                </div>
                <div className="flex items-center">
                  <div>💍 {t('母语外您还会哪种语言')}：</div>
                  <div>{item.secondLanguage}</div>
                </div>
                <div className="flex items-center">
                  <div>💍 {t('第二语言是否可以说的流利')}：</div>
                  <div>{item.fluentLanguage}</div>
                </div>
                <div className="flex items-center">
                  <div>💍 {t('职业')}：</div>
                  <div>{item.occupation}</div>
                </div>
                <div className="flex items-center">
                  <div>💍 {t('性格')}：</div>
                  <div>{item.personality}</div>
                </div>
                <div className="flex items-center">
                  <div>💍 {t('爱好和兴趣才能')}：</div>
                  <div>{item.otherExpertise}</div>
                </div>
                <div className="flex items-center">
                  <div>🩸 {t('月经一般持续几天')}：</div>
                  <div>{item.menstrualTime}</div>
                </div>
                <div className="flex items-center">
                  <div>🩸 {t('最后一次月经 ')}：</div>
                  <div>{item.lastMenstrual}</div>
                </div>
                <div className="flex items-center">
                  <div>👶 {t('运动习惯')}：</div>
                  <div>{item.exerciseHabit}</div>
                </div>
              </div>
              <div>
                <h2 className="text-2xl text-gray-800 mb-2 border-b-2 border-[#E3F2DF] pb-1">{t('联系方式')}</h2>
                <div className="flex items-center mb-2">
                  <div>📞 {t('联系电话')}：</div>
                  <div className="ml-1">{item.contactPhone}</div>
                </div>
                <div className="flex items-center mb-2">
                  <div>⚠️ {t('紧急联系人电话')}：</div>
                  <div className="ml-1">{item.emContactPhone}</div>
                </div>
                <div className="flex items-center">
                  <div>💬 {t('三方聊天软件')}：</div>
                  <div className="ml-1">{item.chatSoftware}</div>
                </div>
                <div className="flex items-center mb-2">
                  <div>🏠 {t('家庭住址')}：</div>
                  <div className="ml-1">{item.address}</div>
                </div>
              </div>
            </div>}
            {/* SM页面 */}
            {type === 'SD' && <div>
              <div className="mb-5">
                <div className="flex items-center">
                  <div>👤 {t('姓名')}：</div>
                  <div>{item.name}</div>
                </div>
                <div className="flex items-center">
                  <div>📏 {t('年龄')}：</div>
                  <div>{item.age}</div>
                </div>
                <div className="flex items-center">
                  <div>📏 {t('身高')}：</div>
                  <div>{item.height}</div>
                </div>
                <div className="flex items-center">
                  <div>⚖️ {t('体重')}：</div>
                  <div>{item.weight}</div>
                </div>
                <div className="flex items-center">
                  <div>🩸 {t('血型')}：</div>
                  <div>{item.blood}</div>
                </div>
                {token && <div className="flex items-center">
                  <div>🪙 {t('价格')}：$</div>
                  <div>{item.price}</div>
                </div>}
              </div>
              <div>
                <h2 className="text-2xl text-gray-800 mb-2 border-b-2 border-[#E3F2DF] pb-1">{t('联系方式')}</h2>
                <div className="flex items-center">
                  <div>📞 {t('联系电话')}：</div>
                  <div>{item.contactPhone}</div>
                </div>
                <div className="flex items-center">
                  <div>⚠️ {t('紧急联系人电话')}：</div>
                  <div>{item.emContactPhone}</div>
                </div>
                <div className="flex items-center">
                  <div>💬 {t('三方聊天软件')}：</div>
                  <div>{item.chatSoftware}</div>
                </div>
                <div className="flex items-center">
                  <div>🏠 {t('家庭住址')}：</div>
                  <div>{item.address}</div>
                </div>
              </div>
            </div>}
          </div>
        </div>
      </div>}
      {showInfo && <Button onClick={back} icon={<LeftOutlined />} className='fixed top-8 left-8 text-white bg-[#79A581]'>返回</Button>}
      <Footter />
      <Service />
      <Login show={showLogin} onEvent={onCloseLogin} />
      </>
  );
};

export default List;